/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.user;

import com.servengine.entry.EntryActionForm;
import com.servengine.entry.Entry;

import java.io.IOException;

import java.util.Collection;

import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class MessageActions extends com.servengine.entry.EntryActions 
{
	private static org.apache.commons.logging.Log log=org.apache.commons.logging.LogFactory.getLog(AdminActions.class.getName());
//	MailRelayLocal mailRelay;
	public void initAction(javax.naming.Context context)
	{
		super.initAction(context);
		/*try
		{
		  mailRelay = (MailRelayLocal)initialcontext.lookup("MailRelay/local");
		} catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw new IllegalStateException(e.getMessage());
		}*/
		log.info(getClass().getName() + " initialized");
	}
	public String getModule() { return "user"; }
	public String getItemType() { return "message"; }
/*	protected User getEntryItemOwner(String portalid, Entry entry) throws RemoteException,FinderException
	{
		return usermanager.getUser(portalid,entry.getUser().getPkey());
	}*/
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			ActionForward af = super.unspecified(mapping,form,request,response);
			UserSessionSBean userSession = getUserSession(request);
			EntryActionForm entryForm = (EntryActionForm)form;
		  Entry entry = entryManager.getEntry(userSession.getPortalid(),entryForm.getId());
			if (!entry.getUser().equals(userSession.getUser()) && !new Integer((int)entryForm.getItemId().longValue()).equals(userSession.getUser().getId()))
				throw new IllegalArgumentException();
		  request.setAttribute("entryToUserid",usermanager.getUser(userSession.getPortalid(),(int)entryForm.getItemId().longValue()).getUserid());
			return af;
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			EntryActionForm entryForm = (EntryActionForm)form;
		  if (request.getParameter("userid")!=null && entryForm.getItemId()==null)
				entryForm.setItemId(usermanager.getUser(userSession.getPortalid(),request.getParameter("userid")).getId());
			if (entryForm.getItemId().equals(userSession.getUser().getId()))
				throw new IllegalArgumentException("user.cantSendAMessageToYourself");
		  request.setAttribute("entryToUserid",usermanager.getUser(userSession.getPortalid(),(int)entryForm.getItemId().longValue()).getUserid());
			ActionForward result = super.create(mapping,form,request,response);
			
		  Entry entry = new Entry(userSession.getUser(),userSession.getUser().getEmail(),userSession.getUser().getName(),getModule(),getItemType(),request.getParameter("userid")!=null?usermanager.getUser(userSession.getPortalid(),request.getParameter("userid")).getId():null,true);
			request.setAttribute("entry",entry);
			
			logManager.log(userSession.getPortalid(),userSession.getUser().getId(),"user","MessageActions","create",entryForm.getTitle(),request.getRemoteAddr());
			return result;
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	public ActionForward entries(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			EntryActionForm entryForm = (EntryActionForm)form;
			entryForm.setItemId(userSession.getUser().getId());
			return super.entries(mapping,form,request,response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward myEntries(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
		  UserSessionSBean userSession = getUserSession(request);
		  ActionForward af = super.myEntries(mapping,form,request,response);
		  Collection<Entry> entries = (Collection<Entry>)request.getSession().getAttribute(getModule()+"_"+getItemType()+"_myEntries");
		  HashMap<Integer,User> messageToUsersMap = new HashMap<Integer,User>();
		  for (Entry message: entries)
		    messageToUsersMap.put(message.getItemId(),usermanager.getUser(userSession.getPortalid(),new Integer((int)message.getItemId().longValue())));
		  request.setAttribute("messageToUsersMap",messageToUsersMap);
		  return af;
		} catch (Throwable e)
		{
		  log.error(e.getMessage(), e);
		  saveErrors(request,getErrorsFromException(e));
		  return mapping.findForward("error");
		}
	}
	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
		  UserSessionSBean userSession = getUserSession(request);
			if (((EntryActionForm)form).getId()!=null && !userSession.isAdmin())
				throw new IllegalArgumentException("message.cantChangeSentMessage");
			boolean newEntry = ((EntryActionForm)form).getId()==null;
		  ActionForward af = super.store(mapping,form,request,response);

		  EntryActionForm entryForm = (EntryActionForm)form;
			User user = usermanager.getUser(userSession.getPortalid(),entryForm.getItemId());
			if (newEntry && user.getEmail()!=null)
				try
				{
					request.setAttribute("from",userSession.getUserid());
					String html = getServletContextUtils().getResourceAsString(userSession.getUser(),request,response,"/user/newMessageMail.jsp");
					getMailRelay().send(portalmanager.getEmail(userSession.getPortalid()).getAddress(), user.getEmail(), "New Message", null, html);
				} catch (Throwable e)
				{
					if (log.isDebugEnabled())
						log.error(e.getMessage(),e);
					else
						log.error(e.getMessage());
				}
			return af;
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
}
